package com.ErpCoreWeb.Security.Access;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Base.CCompany;
import com.ErpCoreModel.Base.CRole;
import com.ErpCoreModel.Base.CUser;
import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.UI.CMenu;
import com.ErpCoreModel.UI.CRoleMenu;
import com.ErpCoreModel.UI.CUserMenu;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class MenuAccessPanel
 */
@WebServlet("/MenuAccessPanel")
public class MenuAccessPanel extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

	public CUser m_User = null;
    public CCompany m_Company = null;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MenuAccessPanel() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
				response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
        m_User=(CUser)request.getSession().getAttribute("User");
        if (!m_User.IsRole("管理员"))
        {
        	try {
				response.getWriter().print("没有管理员权限！");
	        	response.getWriter().close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        	return ;
        }
        String B_Company_id = request.getParameter("B_Company_id");
		if (Global.IsNullParameter(B_Company_id))
			m_Company = Global.GetCtx(this.getServletContext())
					.getCompanyMgr().FindTopCompany();
		else
			m_Company = (CCompany) Global.GetCtx(this.getServletContext())
					.getCompanyMgr().Find(Util.GetUUID(B_Company_id));
	
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
            GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
        	PostData();
            return ;
        }
	}

    void GetData()
    {
    	String UType = request.getParameter("UType");
    	if(UType==null)
    		UType="";
        String Uid =  request.getParameter("Uid");
        if(Uid==null)
        	Uid="";
        String GroupId = request.getParameter("GroupId");
        UUID guidGroupId = Util.GetEmptyUUID();
        if (!Global.IsNullParameter(GroupId))
            guidGroupId = Util.GetUUID(GroupId);
        CUser user = null;
        CRole role = null;
        StringBuffer sData = new StringBuffer();
        if (UType.equals("0")) //用户
        {
            if (!Global.IsNullParameter(Uid) && !Global.IsNullParameter(GroupId))
            {
                user = (CUser)Global.GetCtx(this.getServletContext()).getUserMgr().Find(Util.GetUUID(Uid));
                LoopGetMenu(sData, user, Util.GetEmptyUUID(), guidGroupId);
            }
        }
        else if (UType.equals("1")) //角色
        {
            if (!Global.IsNullParameter(Uid))
            {
                role = (CRole)m_Company.getRoleMgr().Find(Util.GetUUID(Uid));
                LoopGetMenu( sData, role, Util.GetEmptyUUID(), guidGroupId);
            }
        }

        if(sData.length()==0)
            LoopGetMenu(sData,Util.GetEmptyUUID());
        
        String sJson = "[" + sData.toString() + "]";

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void LoopGetMenu(StringBuffer sData,UUID Parent_id)
    {
        List<CBaseObject> lstObj= Global.GetCtx(this.getServletContext()).getMenuMgr().GetList();
        for (CBaseObject obj : lstObj)
        {
            CMenu menu = (CMenu)obj;
            if (!menu.getParent_id().equals(Parent_id))
                continue;
            StringBuffer sChildren = new StringBuffer();
            LoopGetMenu( sChildren, menu.getId());

            String sIconUrl = String.format("../../%s/MenuIcon/default.png",
                Global.GetDesktopIconPathName());
            if (menu.getIconUrl().length()>0)
            {
                sIconUrl = String.format("../../%s/MenuIcon/%s",
                    Global.GetDesktopIconPathName(), menu.getIconUrl());
            }
            String sTemp= String.format("{\"id\":\"%s\",\"text\":\"%s\",\"icon\":\"%s\", children: [%s]},",
                menu.getId().toString(), menu.getName(),sIconUrl, sChildren);
            sData.append(sTemp);
        }
        if(sData.length()>0 && sData.charAt(sData.length()-1)==(','))
        	sData.deleteCharAt(sData.length()-1);
    }
    void LoopGetMenu(StringBuffer sData, CUser user, UUID Parent_id, UUID UI_DesktopGroup_id)
    {
        List<CBaseObject> lstObj = Global.GetCtx(this.getServletContext()).getMenuMgr().GetList();
        for (CBaseObject obj : lstObj)
        {
            CMenu menu = (CMenu)obj;
            if (!menu.getParent_id().equals(Parent_id))
                continue;
            StringBuffer sChildren = new StringBuffer();
            LoopGetMenu( sChildren, user, menu.getId(), UI_DesktopGroup_id);
            String sIsCheck = "";
            
            if (user.getUserMenuMgr().FindByMenu(menu.getId(), UI_DesktopGroup_id) != null)
                sIsCheck = "\"ischecked\":\"true\",";

            String sIconUrl = String.format("../../%s/MenuIcon/default.png",
                Global.GetDesktopIconPathName());
            if (menu.getIconUrl().length()>0)
            {
                sIconUrl = String.format("../../%s/MenuIcon/%s",
                    Global.GetDesktopIconPathName(), menu.getIconUrl());
            }
            String sTemp = String.format("{\"id\":\"%s\",\"text\":\"%s\",%s \"icon\":\"%s\",children: [%s]},",
                menu.getId().toString(), menu.getName(), sIsCheck, sIconUrl, sChildren.toString());
            sData.append(sTemp);
        }
        if(sData.length()>0 && sData.charAt(sData.length()-1)==(','))
        	sData.deleteCharAt(sData.length()-1);
    }
    void LoopGetMenu(StringBuffer sData, CRole role, UUID Parent_id, UUID UI_DesktopGroup_id)
    {
        List<CBaseObject> lstObj = Global.GetCtx(this.getServletContext()).getMenuMgr().GetList();
        for (CBaseObject obj : lstObj)
        {
            CMenu menu = (CMenu)obj;
            if (!menu.getParent_id().equals(Parent_id))
                continue;
            StringBuffer sChildren = new StringBuffer();
            LoopGetMenu( sChildren, role, menu.getId(), UI_DesktopGroup_id);
            String sIsCheck = "";
            if (role.getRoleMenuMgr().FindByMenu(menu.getId(), UI_DesktopGroup_id) != null)
                    sIsCheck = "\"ischecked\":\"true\",";

            String sIconUrl = String.format("../../%s/MenuIcon/default.png",
                Global.GetDesktopIconPathName());
            if (menu.getIconUrl().length()>0)
            {
                sIconUrl = String.format("../../%s/MenuIcon/%s",
                    Global.GetDesktopIconPathName(), menu.getIconUrl());
            }
            String sTemp= String.format("{\"id\":\"%s\",\"text\":\"%s\",%s \"icon\":\"%s\",children: [%s]},",
                menu.getId().toString(), menu.getName(), sIsCheck, sIconUrl,sChildren.toString());
            sData.append(sTemp);
        }

        if(sData.length()>0 && sData.charAt(sData.length()-1)==(','))
        	sData.deleteCharAt(sData.length()-1);
    }

    void PostData()
    {
    	String UType = request.getParameter("UType");
        String Uid =  request.getParameter("Uid");
        String GroupId = request.getParameter("GroupId");
        UUID guidGroupId = Util.GetEmptyUUID();
        if (!Global.IsNullParameter(GroupId))
            guidGroupId =Util.GetUUID(GroupId);
        String postData = request.getParameter("postData");
        CUser user = null;
        CRole role = null;
        if (UType.equals("0")) //用户
        {
            user = (CUser)Global.GetCtx(this.getServletContext()).getUserMgr().Find(Util.GetUUID(Uid));
           
            user.getUserMenuMgr().RemoveByDesktopGroupId(guidGroupId);
            String[] arr1= postData.split(",");
            for (String sItem1 : arr1)
            {
                UUID menuid = Util.GetUUID(sItem1);
                CUserMenu UserMenu = new CUserMenu();
                UserMenu.setB_User_id ( user.getId());
                UserMenu.setUI_Menu_id ( menuid);
                UserMenu.setUI_DesktopGroup_id ( guidGroupId);

                CUser user0 = (CUser)request.getSession().getAttribute("User");
                UserMenu.setCreator ( user0.getId());
                user.getUserMenuMgr().AddNew(UserMenu);
            }
            if (!user.getUserMenuMgr().Save(true))
            {
            	try {
					response.getWriter().print("保存失败！");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        }
        else if (UType.equals("1")) //角色
        {
            role = (CRole)m_Company.getRoleMgr().Find(Util.GetUUID(Uid));
            
            role.getRoleMenuMgr().RemoveByDesktopGroupId(guidGroupId);
            String[] arr1 = postData.split(",");
            for (String sItem1 : arr1)
            {
                UUID menuid = Util.GetUUID(sItem1);
                CRoleMenu RoleMenu = new CRoleMenu();
                RoleMenu.setB_Role_id ( role.getId());
                RoleMenu.setUI_Menu_id ( menuid);
                RoleMenu.setUI_DesktopGroup_id ( guidGroupId);

                CUser user0 = (CUser)request.getSession().getAttribute("User");
                RoleMenu.setCreator ( user0.getId());
                role.getRoleMenuMgr().AddNew(RoleMenu);
            }
            if (!role.getRoleMenuMgr().Save(true))
            {
                try {
					response.getWriter().print("保存失败！");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
            }
        }
    }
}
